﻿using DNFImagePacks2Manager.Helpers;
using System.Collections.Generic;
using System.IO;

namespace DNFImagePacks2Manager.NPK
{
    public class NPKIndex
    {

        private byte[] nameBytes;
        private IMGFile? imgFile = null;

        public int Offset { get; set; }
        public int Size { get; set; }
        public string Name { get; private set; }
        public string Subname => Path.GetFileName(Name);
        public byte[] ItemBytes { get; private set; } = [];

        public NPKIndex(BinaryReader reader)
        {
            byte[]offsetBytes = reader.ReadBytes(4);
            byte[]sizeBytes = reader.ReadBytes(4);
            nameBytes = reader.ReadBytes(256);

            Offset = ByteHelper.Bytes2Int(offsetBytes);
            Size = ByteHelper.Bytes2Int(sizeBytes);
            Name = NPKHelper.DecryptIMGName(nameBytes);
        }

        public void SetIMGFile(IMGFile img)
        {
            imgFile = img;
            ItemBytes = img.GetBytes();
        }

        public void ReadItemBytes(BinaryReader reader)
        {
            if (Size > 0)
            {
                reader.BaseStream.Position = Offset;
                ItemBytes = reader.ReadBytes(Size);
            }
        }

        public byte[] GetItemBytes()
        {
            if (imgFile == null)
            {
                if(ItemBytes.Length > 0)
                {
                    return ItemBytes;
                }
                else
                {
                    return [];
                }
            }
            else
            {
                return imgFile.GetBytes();
            }
        }

        public IMGFile? GetIMGFile()
        {
            if (Size > 0)
            {
                imgFile ??= IMGFile.ReadFromByte(ItemBytes);
            }
            return imgFile;
        }

        public IMGFile? GetIMGFile(BinaryReader reader)
        {
            if (Size > 0)
            {
                reader.BaseStream.Position = Offset;
                imgFile = IMGFile.ReadIMGFile(reader);
            }
            return imgFile;
        }

        public byte[] GetBytes()
        {
            List<byte> byteList = [];
            byteList.AddRange(ByteHelper.Int2Bytes(Offset));
            byteList.AddRange(ByteHelper.Int2Bytes(Size));
            byteList.AddRange(nameBytes);
            return [.. byteList];
        }
    }
}
